package com.westar.core.controller;

import com.westar.base.businessUtil.EditAffairUtil;
import com.westar.base.cons.Constant;
import com.westar.base.exceptions.AffariBusinessException;
import com.westar.base.exceptions.SelfHttpException;
import com.westar.base.model.AffairInfo;
import com.westar.base.model.UserInfo;
import com.westar.base.pojo.Affair;
import com.westar.base.pojo.WestarResult;
import com.westar.base.util.TokenUtil;
import com.westar.base.util.WestarHttpUtil;
import com.westar.core.conf.SysConst;
import com.westar.core.services.AffairEditService;
import com.westar.core.services.SystemLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 现场申请的Controller
 */
@RestController
@RequestMapping("/affair")
@Api(value = "审批办件信息上传到一体化平台信息")
public class AffairEditController {

    private static Logger logger = LoggerFactory.getLogger(AffairEditController.class);

    @Autowired
    private AffairEditService affairEditService;

    @Autowired
    private Environment env;

    /**
     * 添加办件信息
     *
     * @param token  唯一标识
     * @param affair 传递的参数
     */
    @ApiOperation("添加办件信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "token", dataType = "String", required = true, value = "token标识")
    })
    @RequestMapping(value = "/addAffair", method = POST, produces = "application/json")
    public WestarResult affairEdit(String token, Affair affair) {
        //,HttpServletRequest request
        //判定token参数不能为空
        if (StringUtils.isEmpty(token)) {
            return WestarResult.build(-1, "token参数不能为空");
        }
        //取得当前操作人员
        UserInfo sessionUser = TokenUtil.getSessionUser(token);
        //操作人员需要对应维护区域，否则无法查询事项
        if (StringUtils.isEmpty(sessionUser.getAreaCode())) {
            return WestarResult.build(-1, "该账号所在区域未维护！");
        }
        try {
            String actCookie = TokenUtil.getCookie(token, Constant.MODEL_DOTHINGSUI);
//            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//            MultiValueMap<String, MultipartFile> multiValueMap = multipartRequest.getMultiFileMap();
            WestarResult westarResult = affairEditService.addAffair(actCookie,affair,sessionUser,null);

            return westarResult;
        } catch (AffariBusinessException e) {
            return WestarResult.build(-1, e.getMessage());
        } catch (SelfHttpException e) {
            e.printStackTrace();
            if (e.getCode().equals(SelfHttpException.PAGE_RE_LOGIN)) {
                try {
                    token = TokenUtil.getTokenByAccount(sessionUser.getAccount());
                    if (StringUtils.isEmpty(token)) {
                        return WestarResult.build(-1, "token重新登录无效");
                    }
                    return affairEdit(token, affair);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    return WestarResult.build(-1, ex.getMessage() + "重新登录IO异常");
                } catch (SelfHttpException ex) {
                    ex.printStackTrace();
                    return WestarResult.build(-1, ex.getCode().toString() + "重新登录异常");
                }
            } else {
                return WestarResult.build(-1, e.getCode().toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
            return WestarResult.build(-1, e.getMessage() + "受理办件异常");
        }
    }

    @ApiOperation("完成办件")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "affairCode", dataType = "String", required = true, value = "一体化平台受理编号"),
            @ApiImplicitParam(paramType = "query", name = "finishState", dataType = "String", required = true, value = "需要办结的状态 2正常办结 ")
    })
    @RequestMapping(value = "/finishAffair", method = POST, produces = "application/json")
    public WestarResult finishAffair(Integer finishState, AffairInfo affairInfo) {
        //参数暂时屏蔽（仅限于遂宁）
        //, MultiValueMap<String, MultipartFile> multipartFile
        String affairCode = affairInfo.getAffairCode();
        if (StringUtils.isEmpty(affairCode) || "null".equals(affairCode)) {
            return WestarResult.build(-1, "affairCode参数不能为空");
        }
        if (null == finishState) {
            return WestarResult.build(-1, "finishState参数不能为空");
        }
        try {
            WestarResult westarResult = affairEditService.updateAffairFinishState(affairInfo, finishState.toString());
            if (westarResult.getStatus() == 0) {
//                //除开遂宁，其他项目需要传递照片
//                if (StringUtils.isEmpty(SysConst.ITEM_NAME) || !"suining".equals(SysConst.ITEM_NAME)) {
//                    String filebasePath = env.getProperty("dataexchange.filebase_path");
//                    //缓存资料，用于提交数据用
//                    EditAffairUtil.constrMaterial(multipartFile, affairInfo.getAffairCode(), filebasePath);
//                }
            }
            return westarResult;
        } catch (Exception e) {
            e.printStackTrace();
            return WestarResult.build(-1, e.getMessage());
        }
    }
}
